package com.breadenglish.cms.api.app.common.mybatis.interceptor;

import com.breadenglish.cms.api.app.common.anotation.EnablePaging;
import com.breadenglish.cms.api.app.common.context.PagingContextHolder;
import com.breadenglish.cms.api.app.common.page.Page;
import com.breadenglish.cms.api.app.common.page.QueryPage;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


/**
 * Spring 方法拦截器
 * User: guoyao
 * Date: 13-4-17
 * Time: 下午5:23
 */
@Service("pagingInterceptor")
public class PagingInterceptor implements MethodInterceptor {

    private static Logger logger = LoggerFactory.getLogger(PagingInterceptor.class);

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // 判断是否是带有翻页注解
        if (invocation.getMethod().isAnnotationPresent(EnablePaging.class)) {
            checkEnablePaging(invocation);
        }
        // 方法处理
        Object result;
        try {
            result = invocation.proceed();
        } catch (Throwable t) {
            logger.debug("翻页方法处理异常！", t);
            throw t;
        } finally {
            // 清理翻页参数
            clearContextHolder();
        }
        return result;
    }

    private void checkEnablePaging(MethodInvocation invocation) throws Throwable {
        logger.debug(invocation.getThis().getClass().getName() + " 是否是带有翻页的方法：" + invocation.getMethod().isAnnotationPresent(EnablePaging.class));
        // 查找方法中是否有翻页参数
        QueryPage queryPage = null;
        for (Object obj : invocation.getArguments()) {
            if (QueryPage.class.isInstance(obj)) {
                queryPage = (QueryPage) obj;
                break;
            }
        }
        if (queryPage != null) {
            // 设置翻页参数
            addContextHolder(getPage(queryPage));
        }
    }

    /**
     * 获得翻页参数对象
     *
     * @param queryPage Query翻页参数
     * @return
     */
    protected Page getPage(QueryPage queryPage) {
        Page rollPage = new Page();
        //当前页
        Integer page = queryPage.getPage();
        int currentPage = (page != null && page > 0 ? page : 1);
        rollPage.setCurrentPage(currentPage);
        logger.debug("当前页数：[" + currentPage + "]");
        //每页显示条数
        Integer rows = queryPage.getRows();
        int pageSize = (rows != null && rows > 0 ? rows : 10);
        rollPage.setPageSize(pageSize);
        logger.debug("当前页显示条数：[" + pageSize + "]");
        return rollPage;
    }

    public void addContextHolder(Page rollPage) {
        // 设置翻页参数
        PagingContextHolder.setPage(rollPage);
    }

    public void clearContextHolder() {
        // 清理过期的翻页参数
        PagingContextHolder.removePage();
    }

}
